class Event {
  eventMap: Map<string, Set<(args?: unknown) => void>> | null;
  constructor() {
    this.eventMap = null;
  }
  onListen<T = unknown>(name: EventName, cb: (args?: unknown | T) => void) {
    if (this.eventMap && !this.eventMap.has(name)) {
      const set = this.eventMap.get(name);
      // 如果没有该回调
      if (set && !set.has(cb)) {
        set.add(cb);
        // 如果根本没有该方法名
      } else if (!set) {
        this.eventMap.set(name, new Set([cb]));
      }
    } else if (!this.eventMap) {
      this.eventMap = new Map([[name, new Set([cb])]]);
    }
  }
  run<T = unknown>(name: EventName, args?: T) {
    const set = this.eventMap?.get(name);
    if (set) {
      set.forEach((cb) => {
        if (args) {
          cb(args);
        } else {
          cb();
        }
      });
    }
  }
  remove(name: EventName, cb?: (args?: unknown) => void) {
    const set = this.eventMap?.get(name);
    if (cb) {
      if (set?.has(cb)) {
        set.delete(cb);
      }
    } else {
      this.eventMap?.delete(name);
    }
  }
}

export default Event;
